import adminApi from '@/services/adminApi';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import fieldconfig from './fieldconfig';
import UpdateField from './UpdateField';

const FieldList: React.FC<{ modId: number }> = (props) => {
  const [updateFiedShow, setUpdateFiedShow] = useState(0);
  const [filedRow, setFiledRow] = useState<any>({});
  const ref = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '字段标题',
      dataIndex: 'title',
      render: (_) => <a>{_}</a>,
    },
    {
      title: '字段名',
      dataIndex: 'name',
    },
    {
      title: '字段类型',
      dataIndex: 'type',
      valueType: 'select',
      request: async () => fieldconfig.fieldOptions,
    },
    {
      title: '字段定义',
      dataIndex: 'field',
      search: false,
    },
    {
      title: '默认值',
      dataIndex: 'value',
      search: false,
    },
    {
      title: '表单展示',
      dataIndex: 'is_show',
      valueEnum: {
        0: { text: '不显示', status: 'Default' },
        1: { text: '始终显示', status: 'Processing' },
        2: { text: '新增时显示', status: 'Success' },
        3: { text: '编辑时显示', status: 'Error' },
      },
    },
    {
      title: '必填',
      dataIndex: 'is_must',
      valueEnum: {
        true: { text: '必填', status: 'Error' },
        false: { text: '非必填', status: 'Success' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '索引',
      dataIndex: 'indexes',
      valueEnum: {
        true: { text: '是', status: 'Success' },
        false: { text: '否', status: 'Error' },
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      width: 120,
      key: 'option',
      valueType: 'option',
      render: (_, record, _index, action) => [
        <a
          key="attrEdit"
          onClick={() => {
            setFiledRow(record);
            setUpdateFiedShow(2);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="attrDel"
          title={`确认删除吗?`}
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            const res = await adminApi.cms.AdminapiCmsAttrdel({ id: record.id });
            if (res.errorCode === '0') {
              action?.reload();
              message.success('删除成功');
            } else {
              message.error('删除失败');
            }
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <>
      <ProTable
        actionRef={ref}
        columns={columns}
        params={{ mod_id: props.modId }}
        request={async (params: any, sorter, filter): Promise<any> => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sorter, filter);
          const data = await adminApi.cms.AdminapiCmsAttrlist(params);
          return data;
        }}
        rowKey="id"
        pagination={false}
        dateFormatter="string"
        // rowSelection={{
        //   // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
        //   // 注释该行则默认不显示下拉选项
        //   selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        //   defaultSelectedRowKeys: [],
        // }}
        // tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
        //   <Space size={24}>
        //     {console.log(selectedRows)}
        //     <span>
        //       已选 {selectedRowKeys.length} 项
        //       <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
        //         取消选择
        //       </a>
        //     </span>
        //     {/* <span>{`容器数量: ${selectedRows.reduce((pre, item) => pre + item.key, 0)} 个`}</span>
        //         <span>{`调用量: ${selectedRows.reduce((pre, item) => pre + item.key, 0)} 次`}</span> */}
        //   </Space>
        // )}
        // tableAlertOptionRender={() => {
        //   return (
        //     <Space size={16}>
        //       <a>批量删除</a>
        //       <a>导出数据</a>
        //     </Space>
        //   );
        // }}
        toolBarRender={() => [
          <Button key="addField" type="primary" onClick={() => setUpdateFiedShow(1)}>
            新建字段
          </Button>,
        ]}
      />
      <UpdateField
        onCancel={() => {
          setUpdateFiedShow(0);
          setFiledRow({});
        }}
        onSubmit={async (values: any) => {
          values.mod_id = props.modId;
          console.log(values);
          let res: any = {};
          if (updateFiedShow === 1) {
            res = await adminApi.cms.AdminapiCmsAttradd({}, values);
          } else if (updateFiedShow === 2) {
            values.id = filedRow.id;
            res = await adminApi.cms.AdminapiCmsAttredit({}, values);
          }
          if (res?.errorCode == '0') {
            message.success('操作成功');
            // 刷新
            ref?.current?.reload();
            setUpdateFiedShow(0);
          } else {
            message.error('操作失败');
          }
        }}
        updateFiedShow={updateFiedShow}
        values={filedRow || {}}
      />
    </>
  );
};
export default FieldList;
